package com.zwh.aop.modules.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zwh.aop.modules.service.TestAspectService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author zwh
 * @date 2021/10/12 14:41
 **/
@Slf4j
@Controller
@RequestMapping(value = "testAop")
public class TestAspectController {

    @Autowired
    private TestAspectService testAspectService;
    /**
     * 测试方法切入点
     */
    @RequestMapping(value = "testMethodPoint1")
    @ResponseBody
    public void testMethodPoint1(@RequestBody Map<String,Object> data, HttpServletRequest request) throws IOException {

        log.info("读取第一次");
        String body = inputStream2String(request.getInputStream());

        log.info("读取第二次");
        String body2 = inputStream2String(request.getInputStream());

        log.info("方法执行1");
        testAspectService.testAnnotationPoint();
    }

    @RequestMapping(value = "test2")
    @ResponseBody
    public void testMethodPoint1(@RequestParam MultipartFile aa, HttpServletRequest request) throws IOException {

        testAspectService.testAnnotationPoint();
    }

//    @RequestMapping(value = "testMethodPoint")
//    @ResponseBody

    /**
     * 将inputStream里的数据读取出来并转换成字符串
     *
     * @param inputStream inputStream
     * @return String
     */
    private String inputStream2String(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("", e);
            throw new RuntimeException(e);
        }
        return sb.toString();
    }
}
